namespace Coding4Fun.Maelstrom.Common
{
	public static partial class UrlHelper
	{
		public static UrlData ParseUrl(string uri)
		{
			var data = new UrlData 
			{
				NormalizedHealth = double.MinValue,

				IsDamage = false,
				IsScore = false,
				IsGameState = false,

				GameStateAnimation = GameStateAnimation.Invalid,

				Invalid = true
			};

			try
			{
				var urlInParts = uri.ToLower().TrimStart(UriPathSeparator).Split(QueryStringMarker);

				// doing everything via query string
				if (urlInParts.Length > 1)
				{
					var querystring = urlInParts[1].Split(QueryStringSeparator);

					foreach (var queryString in querystring)
					{
						var keyValuePair = queryString.Split(QueryStringParamSeparator);

						if (keyValuePair.Length != 2)
							continue;

						var value = keyValuePair[1];

						switch (keyValuePair[0])
						{
							case QueryString_GameState:
								data.GameStateAnimation = ParseGameStateAnimation(value);
								data.IsGameState = true;
								break;

							case QueryString_NormalizedHealth:
								data.NormalizedHealth = ParseDouble(value);
								break;

							case QueryString_Damage:
								data.IsDamage = ParseBool(value);
								break;
							case QueryString_Score:
								data.IsScore = ParseBool(value);
								break;
						}
					}
				}

				data.Invalid = false;
			}
			catch
			{
				data.Invalid = true;
			}

			return data;
		}

		private static bool ParseBool(string value)
		{
			return (value == "true" || value == "1");
		}

		private static double ParseDouble(string value)
		{
			try
			{
				return double.Parse(value);
			}
			catch
			{
				return double.MinValue;
			}
		}

		private static GameStateAnimation ParseGameStateAnimation(string value)
		{
			try
			{
				return (GameStateAnimation)int.Parse(value);
			}
			catch
			{
				return GameStateAnimation.Invalid;
			}
		}
	}
}
